var app=angular.module('myApp', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
		when('/', {templateUrl: 'payment.html', controller: paycont}).
		when('/cancel/', {templateUrl: 'payment.html', controller: paycont}). 
		otherwise({redirectTo: '/'});
}]);

function paycont($scope, $http,$window,$location,$filter)
 {
    $scope.count = 0;    
	$scope.Math = window.Math;	
	$scope.socdata = {}; 
	$scope.cust_arr = [];
	$scope.dt_arr = [];
	var d = new Date();	
	$scope.paydate='';
	
	$http.get('paydata.php?q=1').success(function(data) {
		$scope.socdata = data;						
    });		
	
	$http.get('paydata.php?q=4').success(function(data) {	
		$scope.paymentdata = data;
		for(var i=0;i<data.length;i++)
		{
			$scope.dt_arr[i]=data[i].paydate;
			$scope.cust_arr[i]=data[i].cname;
		}		
    });
	
	$scope.getmbs=function()
	{		
		$http.get('paydata.php?q=2&soc='+$scope.paynow.soc).success(function(data) {			
			if(data == 'null')
				$scope.memroom[0].room="No entries...";
			else
				$scope.memroom = data;			
			$scope.mbdata = null;
		});				
	}

	$scope.getmbdata=function()
	{		
		var sql='paydata.php?q=3&soc='+$scope.paynow.soc+'&room='+$scope.paynow.member;		
		$http.get(sql).success(function(data) {					
			$scope.mbdata = data;				
		});	
		$scope.paydate=d.getFullYear()+"-"+("0" +(d.getMonth()+1)).slice(-2)+"-"+("0" + d.getDate()).slice(-2);
	}
	
	$scope.saverec=function(pay)
	{	
		pay.amt=document.getElementById('p_amt').value;
		pay.paydate=document.getElementById('dtp1').value;		
		if(!pay.soc || !pay.member || !pay.amt || !pay.paydate)
			alert("Please enter all mandatory fields marked with *");
		else 
		{
			var dupl = false;
			for(var i=0;i<$scope.cust_arr.length;i++)
			{				
				if(pay.cname == $scope.cust_arr[i] && pay.paydate == $scope.dt_arr[i])
					dupl=true;
			}
								
			if(dupl)
				alert("Payment for "+pay.cname+" on this day is already made");
			else{				
				var sql='pay_cud.php?dataset='+JSON.stringify(pay);	
				$http.post(sql).success(function(data) {				
					alert("Data saved successfully");	
					if(!pay.sms)
						$scope.cancel();
				});				
				if(pay.sms)
				{
					var url='getsendsms.php?rcv='+pay.cname+'&amt='+pay.amt+'&phone='+pay.phone;
					$http.post(url).success(function(data) {			
						$scope.sendsms(data);		
						$scope.cancel();
					});
				}			
			}
		}
	};
	
	$scope.sendsms= function(url)
	{
		alert("Sending SMS");
		$.post( url, function() {
		  alert( "success" );
		});				
	}
	
	$scope.cancel= function()
	{		 
		$scope.activePath = null;
		$scope.activePath = $location.path('payment.php');	
	};
 }
